//
//  FileEncAndDec.cpp
//  firebkball
//
//  Created by ren jian on 18/5/28.
//
//

#include "FileEncAndDec.h"
#include "MyConst.h"
#include "Base64Util.h"

std::string FileEncAndDec::encStr(const string es)
{
    unsigned char* str = (unsigned char *)es.c_str();
    unsigned long strSize = 0L;
    unsigned char* enc = TEAUtil::encrypt(str, es.length(), MyConst::TEA_KEY_FILE, &strSize);
    //base64
    std::string encStr = Base64Util::encode(enc, strSize);
    delete enc;
    return encStr;
}

std::string FileEncAndDec::encLong(long es)
{
    char ss[40];
    sprintf(ss, "%ld", es);
    std::string str = (std::string)ss;
    
    return encStr(str);
}


std::string FileEncAndDec::encInt(int es)
{
    char ss[20];
    sprintf(ss, "%d", es);
    std::string str = (std::string)ss;
    
    return encStr(str);
}

std::string FileEncAndDec::encBool(bool es)
{
    char ss[10];
    sprintf(ss, "%d", es);
    std::string str = (std::string)ss;
    
    return encStr(str);
}

std::string FileEncAndDec::decStr(const string ds)
{
    //base64
    std::string dsStr = Base64Util::decode(ds);
    //解密
    unsigned long strSize = 0;
    unsigned char *strTxt = TEAUtil::decrypt((unsigned char*)dsStr.c_str(), dsStr.length(), MyConst::TEA_KEY_FILE, &strSize);
    unsigned char* strTxt2=TEAUtil::convert2str(strTxt, strSize);
    delete[] strTxt;
    dsStr =  (std::string)((char *)strTxt2);
    delete[] strTxt2;
    return dsStr;
}

int FileEncAndDec::decInt(const string ds)
{
    std::string dsStr = decStr(ds);
    int number = std::atoi(dsStr.c_str());
    //    CCLOG("number: %d", number);
    return number;
}

bool FileEncAndDec::decBool(std::string ds)
{
    std::string dsStr = decStr(ds);
    bool isOK = std::atoi(dsStr.c_str());
    return isOK;
}

const std::string FileEncAndDec::decJsonFile(const char *fileUrl)
{
    //    log("decJsonFile=%s \n",fileUrl);
    unsigned long encSize = 0;
    //    unsigned char *enc = AhaFileUtil::getFileData(fileUrl, "rb", &encSize);
    Data data =FileUtils::getInstance()->getDataFromFile(fileUrl);
    unsigned char *enc_=data.getBytes();
    encSize=data.getSize();
    
    unsigned long pntSize = 0;
    unsigned char *pnt = TEAUtil::decrypt(enc_, encSize, MyConst::TEA_KEY_FILE, &pntSize);
    
    unsigned char* strTxt2=TEAUtil::convert2str(pnt, pntSize);
    //copy and delete
    std::string dsStr =  (std::string)((char *)strTxt2);
    
    
    //    log("\t\t dsStr = %s",dsStr.c_str());
    delete [] pnt;
    delete [] strTxt2;
    
    return dsStr;
}


